﻿using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using mozhi.smarterp.AuthorCenter.Departments;
using mozhi.smarterp.AuthorCenter.Departments.Repositories;
using mozhi.smarterp.AuthorCenter.Users.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
using Volo.Abp.Security.Claims;

namespace mozhi.smarterp.AuthorCenter.Users
{
    public class CustomUserClaimsPrincipalFactory : AbpUserClaimsPrincipalFactory, ITransientDependency
    {
        private IDepartmentRepository _departmentRepository;
        private IUserDataPermissionRepository _userDataPermissionRepository;

        public CustomUserClaimsPrincipalFactory(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> options,
            ICurrentPrincipalAccessor currentPrincipalAccessor, IAbpClaimsPrincipalFactory abpClaimsPrincipalFactory , IDepartmentRepository departmentRepository ,
            IUserDataPermissionRepository userDataPermissionRepository) :
            base(userManager, roleManager, options, currentPrincipalAccessor, abpClaimsPrincipalFactory)
        {
            _departmentRepository = departmentRepository;
            _userDataPermissionRepository = userDataPermissionRepository;
        }

        public override async Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
        {
            var principal = await base.CreateAsync(user);

            ClaimsIdentity claimsIdentity = principal.Identities.First();

            if (user.ExtraProperties.ContainsKey("DepartmentId"))
            {
                var departmentId = (Guid?)user.ExtraProperties["DepartmentId"];

                if (departmentId.HasValue)
                {
                    claimsIdentity.AddIfNotContains(new Claim("departmentId", departmentId.ToString()));
                }   
            }

            var userDataPermission = await _userDataPermissionRepository.FindAsync(user.Id);

            if(userDataPermission!=null)
            {
                claimsIdentity.AddIfNotContains(new Claim("dataPermissionId", userDataPermission.Id.ToString()));
            }


            return principal;
        }
    }
}
